package cn.zhxu.toys.captcha.impl;

import cn.zhxu.toys.cache.CacheService;
import cn.zhxu.toys.captcha.Captcha;
import cn.zhxu.toys.captcha.CaptchaStorage;

/**
 * 验证码 Cache 存储器
 * @author Troy
 */
public class DefaultCaptchaStorage implements CaptchaStorage {

	/** 缓存服务 */
	private CacheService cacheService;

	/** 缓存前缀 */
	private String keyPrefix = "captcha";

	/** 存储时间 */
	private int cacheSeconds = 1800;


	public DefaultCaptchaStorage() {
	}

	public DefaultCaptchaStorage(CacheService cacheService) {
		this.cacheService = cacheService;
	}

	@Override
	public Captcha findCaptcha(String captchaId) {
		String data = cacheService.cache(key(captchaId), String.class);
		if (data != null) {
			return CaptchaBean.parse(data);
		}
		return null;
	}
	
	@Override
	public void save(String captchaId, String code, int expireSeconds) {
		CaptchaBean captcha = new CaptchaBean();
		captcha.setCode(code);
		captcha.setExpireTime(System.currentTimeMillis() / 1000 + expireSeconds);
		cacheService.cache(key(captchaId), cacheSeconds, captcha.serialize());
	}

	@Override
	public void save(String captchaId, Captcha captcha) {
		if (captcha != null) {
			cacheService.cache(key(captchaId), cacheSeconds, captcha.serialize());
		}
	}

	@Override
	public void delete(String captchaId) {
		cacheService.delete(key(captchaId));
	}

	protected String key(String captchaId) {
		return keyPrefix + ":" + captchaId;
	}

	public String getKeyPrefix() {
		return keyPrefix;
	}

	public void setKeyPrefix(String keyPrefix) {
		this.keyPrefix = keyPrefix;
	}

	public CacheService getCacheService() {
		return cacheService;
	}

	public void setCacheService(CacheService cacheService) {
		this.cacheService = cacheService;
	}

	public int getCacheSeconds() {
		return cacheSeconds;
	}

	public void setCacheSeconds(int cacheSeconds) {
		this.cacheSeconds = cacheSeconds;
	}

}
